package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否登录
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
       // 将Servlet类型的request，respons转换为HttpServlet的类型
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        //1.获取本次请求的URI
        String requestURI = request.getRequestURI().toString();
        String[] url=new String[]{
                "/employee/login",
                "/backend/",
                "/front/",
                "/user/sendMsg",
                "/user/login"
        };
        //2.判断本次请求是否需要被处理 如果不需要处理 则直接放行
        for (String s : url) {
            if (requestURI.contains(s)){
                filterChain.doFilter(request,response);
                return;
            }
        }
        //3.判断登录状态 如果已经登陆则直接放行
        Long id = (Long) request.getSession().getAttribute("employee");
        if(id!=null){
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request,response);
            return;
        }
        if (request.getSession().getAttribute("user")!=null){
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));
            Long userid = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userid);
            filterChain.doFilter(request,response);
            return;
        }
        //4.如果未登录则返回未登录的结果
        if (id==null){
           servletResponse.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
            return;
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("拦截了");
        Filter.super.init(filterConfig);
    }
}
